import { FunctionComponent, useEffect, useMemo, useState } from "react"
import Style from "./index.less"
import { RightOutline } from 'antd-mobile-icons'
import ShopCart from "./components/shopcart/index"
import Sell from "./components/sell/index"
import { history } from "umi"
import httpService from "@/core/http.service"
import api from "@/core/api.config"

export interface IPropsIndex { }

export type ISell = Array<{
  current?: boolean;
  id: number;
  name: string;
  foods: Array<{
    id: number;
    name: string;
    price: number;
    oldPrice: number;
    rating: number;
    sellCount: number;
    nums: number
    image: string;
  }>;
}>
export type IStore = {
  avatar: string;
  backImage: string;
  bulletin: string;
  deliveryPrice: number;
  deliveryTime: number;
  description: string;
  id: number;
  minPrice: number;
  name: string;
  reachPrice: number;
  subtractPrice: number;
}


const Index: FunctionComponent<IPropsIndex> = () => {

  const [data, setData] = useState<ISell>([]);
  const [store, setStore] = useState<Partial<IStore>>({})

  const toLogin = () => {
    localStorage.removeItem("userId");
    history.replace("/login")
  }

  const buyNums = useMemo(() => {
    return data.reduce((total, current) => {
      return total + current.foods.reduce((t, c) => t + c.nums, 0)
    }, 0)
  }, [data])

  useEffect(() => {
    httpService.request<ISell>({
      method: 'GET',
      url: api.product.getProductList,
      cacheFor: 60 * 10 * 1000
    }).then((res) => {
      if (typeof (res) === 'string') return;
      const result = res.map((p, i) => ({ ...p, current: i == 0, foods: p.foods.map(k => ({ ...k, nums: 0 })) }))
      httpService.request({
        method: 'GET',
        url: api.user.getOrder
      }).then(order => {
        if (order && Object.keys(order)) {
          Object.entries(order).forEach(([key, val]) => {
            for (let i = 0; i < result.length; i++) {
              for (let j = 0; j < result[i].foods.length; j++) {
                if (result[i].foods[j].id === Number(key)) {
                  result[i].foods[j].nums = Number(val)
                }
              }
            }
          })
        }
        setData(result)
      }).catch(_ => {
        setData(result)
      })
    })
    httpService.request<IStore>({
      method: "GET",
      url: api.store.getStoreInfo,
      data: { id: 1 },
      cacheFor: 60 * 10 * 1000
    }).then(res => {
      if (typeof (res) === 'string') return;
      setStore(res)
    })
  }, [])

  useEffect(() => {
    if (data.length) {
      const info: Record<number, number> = {}
      data.forEach(foods => {
        foods.foods.forEach(item => {
          if (item.nums) Reflect.set(info, item.id, item.nums)
        })
      })
      httpService.request({
        method:'POST',
        url: api.user.updateOrder,
        data: {info: JSON.stringify(info)}
      })
    }
  }, [buyNums])

  return (
    <div className={Style.index}>
      <div className={Style.index_header} style={{ backgroundImage: `url('${store.backImage}')` }}>
        <div className={Style.index_header_body}>
          <img src={store.avatar} className={Style.body_icon} />
          <div className={Style.body_store}>
            <div className={Style.body_store_name}>{store.name}</div>
            <div className={Style.body_store_send}>{store.description}/{store.deliveryTime}分钟送达</div>
            <div className={Style.body_store_reduce}>在线支付满{store.reachPrice}减{store.subtractPrice}元</div>
          </div>
          <div className={Style.index_header_logout} onClick={() => toLogin()}>
            退出登录
            <RightOutline fontSize={10} />
          </div>
        </div>
        <div className={Style.index_header_foot}>
          <div className={Style.index_header_foot_txt}>{store.bulletin}</div>
          <RightOutline fontSize={10} />
        </div>
      </div>
      <div className={Style.index_body}>
        {
          data && data.length ?
            <Sell data={data} onChange={(e: ISell) => setData(e)} /> :
            null
        }
      </div>
      <div className={Style.index_shopcart}>
        {
          data && data.length && store.name ?
            <ShopCart store={store} data={data} onChange={(e: ISell) => {
              setData(e)
            }} /> :
            null
        }
      </div>
    </div>
  )
}

export default Index